package cn.edu.zafu.bigdata.Yum;

import java.io.*;
public class SortThread extends Thread {
    private PrintWriter out = null;
    private BufferedReader in = null;

    public SortThread(PrintWriter out, BufferedReader in) {
        this.out = out;
        this.in = in;
    }

    //排序线程的线程体
    public void run() {
        int MAXWORDS = 50;
        if (out != null && in != null) {
            try {
                String[] listOfWords = new String[MAXWORDS];
                int numwords = 0;

                while ((listOfWords[numwords] = in.readLine()) != null)
                    numwords++;
                quicksort(listOfWords, 0, numwords - 1);
                for (int i = 0; i < numwords; i++)
                    out.println(listOfWords[i]);
                out.close();
            } catch (IOException e) {
                System.out.println("SortThread run:" + e);
            }
        }
    }
    private static void quicksort(String[] a, int lo0, int hi0) {
        int lo = lo0;
        int hi = hi0;

        // 选择一个基准值（pivot），这里我们选择中间的元素
        String mid = a[(lo0 + hi0) / 2];

        // 分区操作，将数组分为两部分，一部分小于基准值，另一部分大于基准值
        while (lo <= hi) {
            // 从lo开始向右查找大于或等于基准值的元素
            while (lo < hi0 && a[lo].compareTo(mid) < 0) {
                lo++;
            }
            // 从hi开始向左查找小于或等于基准值的元素
            while (hi > lo0 && a[hi].compareTo(mid) > 0) {
                hi--;
            }
            // 如果lo <= hi，交换这两个元素的位置，并且继续分区操作
            if (lo <= hi) {
                String temp = a[lo];
                a[lo] = a[hi];
                a[hi] = temp;
                lo++;
                hi--;
            }
        }

        // 递归排序基准值左边的子数组
        if (lo0 < hi) {
            quicksort(a, lo0, hi);
        }
        // 递归排序基准值右边的子数组
        if (lo < hi0) {
            quicksort(a, lo, hi0);
        }
    }

    // 用于启动快速排序的辅助方法
    public static void quickSortWrapper(String[] a) {
        if (a == null || a.length == 0) {
            return;
        }
        quicksort(a, 0, a.length - 1);
    }
}